<template>
  <div class="tdlybgdc">
    <div class="tdlybgdc_top">
      <div class="tdlybgdc_top_text">
        土地利用变更调查
      </div>
      <el-switch
        v-model="switchValue"
        active-color="#409EFF"
        inactive-color="#d1d1d1"
        @change="switchChange"
        :disabled="isdisabled"
      >
      </el-switch>
    </div>
    <div
      class="tdlybgdc_bottom"
      v-if="TDresulrData.length && TDresulrData[0].ha != 0"
    >
      <div id="qstViews2" style="width:460px;height:150px"></div>
    </div>
    <div v-else class="tdlybgdc_bottom_else">
      <div class="tdlybgdc_bottom_else_content">选址不涉及土地利用变更调查</div>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import { mapActions, mapState } from "vuex";
import { getXzRegion } from "../../../../../api/connect.js";
import tableNames from "../../left/tableNames.json";
import { editMap } from "../../../../../utils/map.js";

export default {
  data() {
    return {
      option: {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
        },
        grid: {
          top: "14%",
          left: "2%",
          right: "5%",
          bottom: "5%",
          containLabel: true,
        },
        // dataZoom: [
        //   {
        //     show: true,
        //     bottom: 0,
        //     start: 0, //数据窗口范围的起始百分比,表示30%
        //     end: 50, //数据窗口范围的结束百分比,表示70%
        //     startValue: 10, //数据窗口范围的起始数值
        //     endValue: 100,
        //     width: 5,
        //     orient: "horizontal",

        //     brushSelect: false,
        //     zoomLock: true, //锁定滚动区域
        //     // backgroundColor: "rgba(86, 166, 253, 0.1)", //滚动条底部的颜色
        //     borderColor: "rgba(86, 166, 253, 0.3)", // 边框颜色
        //     showDataShadow: false, //去除原始组件上的数据阴影
        //     showDetail: false,
        //     fillerColor: "rgba(86, 166, 253, 0.3)",
        //     dataBackground: {
        //       areaStyle: {
        //         color: "rgba(86, 166, 253, 0.3)",
        //       },
        //     },
        //   },
        //   {
        //     //没有下面这块的话，只能拖动滚动条，鼠标滚轮在区域内不能控制外部滚动条
        //     type: "inside",
        //     xAxisIndex: 0,
        //     zoomOnMouseWheel: false, //滚轮是否触发缩放
        //     moveOnMouseMove: true, //鼠标滚轮触发滚动
        //     moveOnMouseWheel: true,
        //   },
        // ],
        xAxis: [
          {
            type: "category",
            data: [],
            axisLine: {
              show: true, //添加x轴最底下的线
            },
            axisTick: {
              show: false,
            },
            axisLabel: {
              // interval: 0,
              // rotate: 40,
              color: "rgba(255, 255, 255, 0.85);",
              fontFamily: "Tencent",
              fontSize: "12px",
              align: "center",
              textStyle: {
                fontFamily: "Microsoft YaHei",
              },
            },
            nameGap: 15,
          },
        ],
        yAxis: [
          {
            type: "value",
            splitNumber: 4,
            scale: true,
            min: 0,
            boundaryGap: [0.2, 0.2],
            axisLine: {
              show: false,
              lineStyle: {
                color: "white",
              },
            },
            splitLine: {
              show: true,
              lineStyle: {
                color: "rgba(255,255,255,0.1)",
                type: "dashed",
              },
            },
            axisLabel: {
              // formatter: "{value} °C"
              color: "rgba(255,255,255,1)",
              // fontFamily: "monospace",
              fontFamily: "Tencent",
              fontSize: "12px",
            },
          },
        ],
        series: [
          {
            name: "Direct",
            type: "bar",
            barWidth: "30px",
            data: [],
            itemStyle: {
              normal: {
                color: function(params) {
                  var colorList = [
                    "#2276FC",
                    "#57A7FF",
                    "#2276FC",
                    "#57A7FF",
                    "#2276FC",
                    "#57A7FF",
                    "#2276FC",
                    "#57A7FF",
                    "#2276FC",
                    "#57A7FF",
                    "#2276FC",
                    "#57A7FF",
                    "#2276FC",
                  ];
                  return colorList[params.dataIndex];
                },
              },
            },
            label: {
              show: true,
              position: "top",
              formatter: "{c}m²",
              color: "#FFFFFF",
              fontSize: 12,
              fontWeight: 400,
              rotate: 25,
            },
          },
        ],
      },
      //switch的值
      switchValue: false,
      isdisabled: false, //是否禁用
      // 土地利用变更调查的图层加载loading
      tdlybgdcLoading: false,

      // 保存土地利用变更调查的画面数据
      polygondata: [],
      polylinedata: [],
    };
  },
  mounted() {
    this.getEcharts();
    this.changeData();
  },
  watch: {
    polygonTypeId(newVal, oldVal) {
      console.log(newVal, "新的newVal");
    },
  },
  computed: {
    ...mapState("Sjsx", [
      "TDresulrData",
      "unit",
      "isRegion",
      "tuliData",
      "polygonType",
      "polygonTypeId",
    ]),
  },
  methods: {
    ...mapActions({
      setTdlybgdcLoading_act: "Sjsx/setTdlybgdcLoading_act",
      setTuliData_act: "Sjsx/setTuliData_act",
      setTuliPolygonData_act: "Sjsx/setTuliPolygonData_act",
      setTuliPolyLineData_act: "Sjsx/setTuliPolyLineData_act",
      setPolygonType_act: "Sjsx/setPolygonType_act",
    }),
    getEcharts() {
      if (this.TDresulrData.length != 0) {
        var chart = echarts.init(document.getElementById("qstViews2"));
        chart.setOption(this.option);
      }
    },

    // 改变土地柱状图数据
    changeData() {
      if (this.TDresulrData.length != 0) {
        console.log(this.TDresulrData, "土地利用情况");
        console.log(this.unit, "unit");
        this.option.series[0].data = [];
        this.option.xAxis[0].data = [];
        this.TDresulrData.forEach((item) => {
          // this.option.series[0].data.push(item.m2)
          this.option.xAxis[0].data.push(item.subCategory);
          // this.option.series[0].label.formatter = `{c}${this.unit}`;
          // if (this.unit == "m²") {
          //   this.option.series[0].data.push(item.m2);
          //   this.option.series[0].label.formatter = "{c}平方米";
          // } else if (this.unit == "ha") {
          //   this.option.series[0].data.push(item.ha);
          //   this.option.series[0].label.formatter = "{c} 公顷";
          // } else if (this.unit == "mu") {
          //   this.option.series[0].data.push(item.mu);
          //   this.option.series[0].label.formatter = "{c} 亩";
          // }
          this.option.series[0].data.push(item.ha);
          this.option.series[0].label.formatter = "{c} 公顷";
        });
        console.log(this.option.series[0].data, "series");
        console.log(this.option.xAxis[0].data, "xAxis");
        this.getEcharts();
      }
    },

    // 点击后画面
    async getRegionData() {
      try {
        const temp = JSON.parse(
          JSON.stringify(
            tableNames.find(
              (r) => r.layer_chinese_name === "土地利用变更调查（2018）"
            )
          )
        );
        if (this.switchValue == true) {
          const result = await getXzRegion(this.isRegion, temp);
          // debugger;
          const polygondata = [];
          const polylinedata = [];
          let Type = [];

          result.data.map((item, index) => {
            let itemJson = JSON.parse(item);
            Type.push(itemJson.properties.type);
            // console.log(Type, "Type的值");
            const field_value = itemJson.properties.field_value;
            const type = itemJson.properties.type;
            let color; //设置默认颜色
            if (temp.hex instanceof Array) {
              let colorTemp = temp.hex.find(
                (p) => p.field_value === field_value && p.type === type
              );
              if (!colorTemp) {
                //如果没有值
                colorTemp = temp.hex.find((p) => p.field_value === "default");
              }
              color = colorTemp.hex;
            } else {
              color = temp.hex;
            }
            const r = parseInt(color.substr(1, 2), 16) / 255;
            const g = parseInt(color.substr(3, 2), 16) / 255;
            const b = parseInt(color.substr(5, 2), 16) / 255;
            const colorArray = [r, g, b, 1];
            let o = {
              id: "polygon_" + temp.layer_english_name + "_" + index,
              GroupID:"switch_Polygon",
              coordinates: itemJson.geometry.coordinates,
              color: colorArray,
              userData: JSON.stringify(itemJson.properties),
              // color: [
              //   0.2784313725490196,
              //   0.8117647058823529,
              //   0.0745098039215686,
              //   0.7,
              // ], //多边形的填充颜色
              frameColor: [1, 1, 0, 0.8], //边框颜色
              frameThickness: 2, //边框厚度
              intensity: 1, //亮度
              // style: window.PolygonStyle.SingleColor, //单色 请参照API开发文档选取枚举
              style: 0,
              depthTest: false, //是否做深度检测
              // brightness: 1,
              //   coordinateType: 1,
            };
            polygondata.push(o);
            itemJson.geometry.coordinates.forEach((item) => {
              // console.log(item, "item");
              if (
                item instanceof Array &&
                item[0] instanceof Array &&
                item[0][0] instanceof Array
              ) {
                item.forEach((mon) => {
                  polylinedata.push({
                    id: "polyline_" + temp.layer_english_name + "_" + index,
                    GroupID:"switch_Polygon",
                    coordinates: mon, //构成折线的坐标点数组
                    color: [1, 1, 1, 1], //折线颜色
                    userData: JSON.stringify(itemJson.properties),

                    style: 0, //折线样式 参考样式枚举：PolylineStyle
                    thickness: 5, //折线宽度
                    intensity: 1, //亮度
                    flowRate: 0.5, //流速
                    tiling: 0, //材质贴图平铺比例
                    shape: 0, //折线类型 0：直线， 1：曲线
                    depthTest: false, //是否做深度检测
                    coordinateType: 0,
                  });
                });
              } else {
                polylinedata.push({
                  id: "polyline_" + temp.layer_english_name + "_" + index,
                  GroupID:"switch_Polygon",
                  coordinates: item, //构成折线的坐标点数组
                  color: [1, 1, 1, 1], //折线颜色
                  style: 0, //折线样式 参考样式枚举：PolylineStyle
                  userData: JSON.stringify(itemJson.properties),
                  thickness: 5, //折线宽度
                  intensity: 1, //亮度
                  flowRate: 0.5, //流速
                  tiling: 0, //材质贴图平铺比例
                  shape: 0, //折线类型 0：直线， 1：曲线
                  depthTest: false, //是否做深度检测
                  coordinateType: 0,
                });
              }
            });
          });
          // const polygon3ddata = result.data.map((item, index) => {
          //   let itemJson = JSON.parse(item);
          //   console.log(
          //     itemJson.geometry.coordinates,
          //     "itemJson.geometry.coordinates"
          //   );

          //   let o = {
          //     id: "polygon3d_" + temp.layer_english_name + "_" + index,
          //     coordinates: itemJson.geometry.coordinates,
          //     color: [1, 1, 1, 0.5], //颜色值
          //     height: 150, //3D多边形的高度
          //     intensity: 2.0, //亮度
          //     style: 2,
          //   };
          //   return o;
          // });
          //   temp["polygondata"] = polygondata;
          //   temp["polylinedata"] = polylinedata;
          this.polygondata = polygondata;
          this.polylinedata = polylinedata;

          // 高亮代码
          let polygonType = [];
          console.log(polygondata, "polygondata的值");
          polygondata.forEach((item) => {
            polygonType.push(item);
          });
          console.log(polygonType, "----polygon的Type----");

          polygonType.forEach((item) => {
            item["typeName"] = "土地利用变更调查（2018）";
          });

          // !this.polygonType || this.polygonType.length === 0
          //   ? this.setPolygonType_act([polygonType])
          //   : this.setPolygonType_act([...this.polygonType, polygonType]);
          // console.log(this.polygonType,"---12345---");
          this.setPolygonType_act(polygonType);

          // console.log(this.polygonType,"vuex里的polygonType");

          // console.log(polygondata,"polygondata值");
          // console.log(polylinedata, "polylinedata值");
          this.setTuliPolygonData_act({
            text: "土地利用变更调查（2018）",
            ids: polygondata,
          }); // 将画面的数据传到图例中
          this.setTuliPolyLineData_act({
            text: "土地利用变更调查（2018）",
            ids: polylinedata,
          }); // 将画线的数据传到图例中

          // await window.__g.polyline.add(polylinedata.slice(0,3500));
          // await window.__g.polygon.add(polygondata.slice(0,3500));

          // const tmp = polylinedata.slice(3500,polylinedata.length);
          // debugger;
          // const length = polygondata.length;   // if length=4500

          // 调用一次性画3000条数据的方法
          await editMap(polylinedata, 1);
          await editMap(polygondata, 2);

          this.tdlybgdcLoading = false;
          this.setTdlybgdcLoading_act(this.tdlybgdcLoading);

          // 过滤
          let filterHex = temp.hex.filter((item) => Type.includes(item.type));
          console.log(filterHex, "filterHex");
          temp.hex = filterHex;
          temp.hex.unshift({
            field_value: "default",
            hex: "#808080",
            layer_class_field: "SEN_LIN_LB",
            type: "其他",
          });

          console.log(this.$store.state, "this.$store.state");
          // 判断vuex中是否有存储图例，无则直接加入，有则追加加入
          !this.tuliData || this.tuliData.length === 0
            ? this.setTuliData_act([temp])
            : this.setTuliData_act([...this.tuliData, temp]);
          // this.$store.dispatch(
          //   "Sjsx/setTdlybgdcLoading_act",
          //   this.tdlybgdcLoading
          // );
          // this.$store.dispatch("Sjsx/setTuliData_act", temp.hex);

          // for (let i = 0; i < length; ) {
          //   const limit = i + skip;
          //   if (limit > length) {
          //     limit = length;
          //   }
          //   const tmp = polygondata.slice(i, limit);
          //   // const tmp2 = polygondata.slice(i,limit);
          //   debugger
          //   await window.__g.polyline.add(tmp);
          //   await window.__g.polygon.add(tmp);
          //   i += skip;
          // }

          // await window.__g.polyline.add(tmp);
          // await window.__g.polygon.add(tmp);

          // await window.__g.polygon.focus(polygondata.map((r) => r.id));
        } else if (this.switchValue == false) {
          if (this.polygondata && this.polygondata instanceof Array) {
            // debugger;
            // window.__g.polygon.updateBegin();
            let polygondataIds = [];
            let polylinedataIds = [];

            this.polygondata.forEach((element) => {
              polygondataIds.push(element.id);
            });
            this.polylinedata.forEach((element) => {
              polylinedataIds.push(element.id);
            });
            await window.__g.polygon.delete(this.polygonTypeId); // 关闭高亮的图层
            await window.__g.polygon.delete(polygondataIds);
            await window.__g.polyline.delete(polylinedataIds);

            // window.__g.polygon.updateEnd();
            console.log("已经删除");
          }
        }
      } catch (error) {
        console.log(error);
        this.$message.error("服务器请求异常，图层加载失败！");
        this.switchValue = false; //请求失败后，将switch框设置为false
        this.tdlybgdcLoading = false;
        this.setTdlybgdcLoading_act(this.tdlybgdcLoading); // 请求失败后，将loading窗关闭
        // this.$store.dispatch(
        //   "Sjsx/setTdlybgdcLoading_act",
        //   this.tdlybgdcLoading
        // );
      }
    },

    // switch的改变
    async switchChange(val) {
      console.log(val, "switch改变");
      this.isdisabled = true;
      // this.$store.dispatch("Sjsx/setTuliData_act", null);

      if (val) {
        if (this.TDresulrData.length && this.TDresulrData[0].ha != 0) {
          this.tdlybgdcLoading = true;
          this.setTdlybgdcLoading_act(this.tdlybgdcLoading);
          // this.$store.dispatch(
          //   "Sjsx/setTdlybgdcLoading_act",
          //   this.tdlybgdcLoading
          // );
          // this.switchValue = val;
          const temp = tableNames.find(
            (r) => r.layer_chinese_name === "土地利用变更调查（2018）"
          );
          console.log(temp.hex, "temp的值");
          await this.getRegionData();
          // this.tdlybgdcLoading = false;
          // this.$store.dispatch(
          //   "Sjsx/setTdlybgdcLoading_act",
          //   this.tdlybgdcLoading
          // );
          // this.$store.dispatch("Sjsx/setTuliData_act", temp.hex);
        } else {
          this.$message.warning("选址不涉及，暂无图层");
          setTimeout(() => {
            this.switchValue = false;
          }, 300);
        }
      } else {
        await this.getRegionData();
        let test = this.tuliData.filter(
          (item) => item.layer_chinese_name != "土地利用变更调查（2018）"
        );
        console.log(test, "test");
        console.log(this.tuliData, "关闭时的tulidata");
        this.setTuliData_act(test);


        // let test2 = this.polygonType.filter(item => {
        //   item.forEach(mon => {
        //     mon.typeName != "土地利用变更调查（2018）"
        //   })
        // })
        // console.log(test2, "test2");
        // console.log(this.polygonType, "关闭时的polygondata");
        // this.setPolygonType_act(test2);

        // this.$store.dispatch("Sjsx/setTuliData_act", null);
      }
      this.isdisabled = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.tdlybgdc {
  margin-top: 25px;
  .tdlybgdc_top {
    display: flex;
    align-items: center;
    background: url("../../../../../assets/images/home/top.png");
    width: 440px;
    background-size: cover;
    .tdlybgdc_top_text {
      padding-left: 16px;
      font-family: OPPOSans;
      font-style: normal;
      font-weight: normal;
      font-size: 20px;
      line-height: 24px;
      color: #ffffff;
    }
  }
  .tdlybgdc_middle {
    padding-left: 15px;
    margin-top: 8px;
    display: flex;
    justify-content: space-between;
    .middle_left {
      font-family: Yu Gothic UI;
      font-style: normal;
      font-weight: normal;
      font-size: 16px;
      line-height: 21px;
      color: #bad3ff;
    }
    .middle_right {
      font-family: HuXiaoBo-NanShen;
      font-style: normal;
      font-weight: normal;
      font-size: 16px;
      line-height: 17px;
      color: #ffffff;
    }
  }
  .tdlybgdc_bottom {
  }
  .tdlybgdc_bottom_else {
    margin: 15px 0 0 15px;
    width: 430px;
    height: 100px;
    background: linear-gradient(180deg, #1f3e72 0%, #112650 100%);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    border-radius: 4px;
    cursor: pointer;
    .tdlybgdc_bottom_else_content {
      font-family: OPPOSans;
      font-style: normal;
      font-weight: normal;
      font-size: 18px;
      line-height: 21px;
      color: rgba(255, 255, 255, 0.85);
      // padding-left: 20px;
    }
  }
}
</style>
